package com.gome.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gome.entitiy.Ryxx;
import com.gome.handler.AuthenticationAccessDeniedHandler;
import com.gome.service.SecurityService;
import com.gome.utils.MyPasswordEncoder;
import com.gome.utils.Result;
import com.gome.utils.ResultCode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(customUserService())
                .passwordEncoder(new MyPasswordEncoder());

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
     //   web.ignoring().antMatchers("/swagger-ui.html","/swagger-resources/**","/v2/**","/webjars/**","/error/**");

        web.ignoring().antMatchers("/v2/api-docs",//swagger api json
                "/swagger-resources/configuration/ui",//用来获取支持的动作
                "/swagger-resources",//用来获取api-docs的URI
                "/swagger-resources/configuration/security",//安全选项
                "/webjars/**",
                "/doc.html",
                "/swagger-ui.html");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .csrf() //跨站
                .disable()  //关闭跨站检测
//                .antMatcher("/swagger-ui.html")
//                .antMatcher("/swagger-resources/**")
//                .antMatcher("/v2/**")
//                .antMatcher("/webjars/**")
//                .antMatcher("/error/**")
                .authorizeRequests()    //验证策略
                .antMatchers("/anonymous/**").hasRole("ANONYMOUS")
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(CustomMetadataSource());
                        o.setAccessDecisionManager(UrlAccessDecisionManager());
                        return o;
                    }
                })
                .anyRequest()   //所有请求
                .authenticated()    //需要验证
                .and()
                .formLogin()
                .loginProcessingUrl("/jservices/ryxx/login")
                .usernameParameter("oc_loginname")
                .passwordParameter("oc_password")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req,
                                                        HttpServletResponse res,
                                                        Authentication auth) throws IOException, ServletException {
                        res.setContentType("application/json;charset=utf-8");
                        Ryxx ryxx =(Ryxx) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                        PrintWriter out = res.getWriter();
                        ObjectMapper om = new ObjectMapper();
                        Result result = new Result(ResultCode.SUCCESS, "登录成功", ryxx);
                        out.write(om.writeValueAsString(result));
                        out.flush();
                        out.close();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req,
                                                        HttpServletResponse res,
                                                        AuthenticationException e) throws IOException, ServletException {
                       res.setContentType("application/json;charset=utf-8");
                        String msg;
                        if (e instanceof BadCredentialsException ||
                                e instanceof UsernameNotFoundException) {
                            msg="账户名或者密码输入错误!";
                        } else if (e instanceof LockedException) {
                            msg="账户被锁定，请联系管理员!";
                        } else if (e instanceof CredentialsExpiredException) {
                            msg="密码过期，请联系管理员!";
                        }

//                        else if (e instanceof AccountExpiredException) {
//                            msg="账户过期，请联系管理员!";
//                        }
                        else if (e instanceof DisabledException) {
                            msg="账户被禁用，请联系管理员!";
                        } else {
                            msg=e.getMessage();
                        }

                        Result result = new Result(ResultCode.FAIL, msg, null);
                        ObjectMapper om = new ObjectMapper();
                        PrintWriter out = res.getWriter();
                        out.write(om.writeValueAsString(result));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                .logout()
                .permitAll()
                .and()
                .exceptionHandling().accessDeniedHandler(AccessDeniedHandler());
    }
    @Bean
    UserDetailsService customUserService(){
        return new SecurityService();
    }
    @Bean
    CustomMetadataSource CustomMetadataSource(){
        return new CustomMetadataSource();
    }

    @Bean
    UrlAccessDecisionManager UrlAccessDecisionManager(){
        return new UrlAccessDecisionManager();
    }
    @Bean
    AccessDeniedHandler AccessDeniedHandler(){
        return new AuthenticationAccessDeniedHandler();
    }



}
